﻿var grid = null;
var PageSize = 25;
var url = "FunctionInf.aspx?";
var permission = null;
var form = null;

$(document).ready(function () {
    permission = JSON.parse($("#hdPermission").val());
    grid = $("#maingrid").ligerGrid({
        columns: [
            { display: 'Function ID', name: 'FunID', width: 100, align: 'left', type: 'string' },
            { display: 'Function 描述', name: 'FunDesc', width: 200, align: 'left', type: 'string' },
            { display: 'Action', name: 'ActDesc', width: 400, align: 'left', type: "text" },
            { display: 'Status', name: 'Flag', width: 60, align: 'center', type: 'string', hide: 'hide' },
            { display: '最后更新', name: 'Lpt', width: 150, align: 'center', isSort: false },
            { display: '操作者', name: 'Whom', width: 100, align: 'center'}],
        pageSize: PageSize, toolbar: {}, url: url + "Action=GetList", width: '100%', height: '99%', dataAction: 'local', pageSizeOptions: [3,20, 25, 30, 35], pageStatMessage: 'Record:{from}-{to} Total:{total} Page Size:{pagesize}', checkbox: true, sortName: 'rID',
        rowAttrRender: function (item, rowid) {
            var color = "";
            if (item.Flag == "I") color = " my-disabled";
            return color;
        },
        onDblClickRow: function (row, rowindex, rowDomElement) {
            if (permission.isEdit) {
                showDetail({
                    RID: row.RID,
                    FunID: row.FunID,
                    FunDesc: row.FunDesc,
                    ActID: row.ActID,
                    ActDesc: row.ActDesc,
                    Flag: row.Flag
                });
            }
        }
    });
    //加载搜索框
    InitForm();

    //加载工具条
    loadToolbar();
})

//搜索条件
function InitForm() {
    $("#txtFunID").ligerTextBox({ label: "Function ID", labelWidth: 80 });
    $("#txtFunName").ligerTextBox({ label: "Function 描述", labelWidth: 100  });
    $("#BtnSearch").click(function () { BtnSearch_Click(); });
}

//工具条
function loadToolbar() {
    var griditems = [];
    if (permission.isEdit)
        griditems[griditems.length] = { click: toolbarClick, text: "新增", img: "../images/add.png", id: "Add" };
    if (permission.isActive)
        griditems[griditems.length] = { click: toolbarClick, text: "生效", img: "../images/Active.png", id: "Enable" };
    if (permission.isInactive)
        griditems[griditems.length] = { click: toolbarClick, text: "失效", img: "../images/Frozen.png", id: "Disable" };
    grid.toolbarManager.set('items', griditems);
}

function toolbarClick(item) {
    switch (item.id) {
        case "Add": BtnAdd_Click(); break;
        case "Enable": BtnActive_Click(); break;
        case "Disable": BtnInactive_Click(); break;
    }
}

/**
* 查询按钮
*/
function BtnSearch_Click() {
    var txtFunID = $("#txtFunID").val();
    var txtFunName = $("#txtFunName").val();
    grid.set('parms', {
        FunID: txtFunID,
        FunDesc: txtFunName
    });
    grid.options.newPage = 1;
    grid.loadData();
}

function BtnAdd_Click() { showDetail({ RID: '' }, true); }

function BtnActive_Click() { ProcessData("A"); }

function BtnInactive_Click() { ProcessData("I"); }

function ProcessData(flag) {
    var rids = GetClientRID();
    if (rids != "") {
        $.ajax({ type: 'post', url: url + 'Action=Process&type=' + flag + '&rids=' + rids, dataType: 'text', cache: false,
            success: function (msg) {
                if (msg == "") { toastrSuccess("Processed successfully/处理成功!"); BtnSearch_Click(); }
                else { toastrError("Processed Failed/处理失败!<br/>" + msg) }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                ShowError("ProcessData()", XMLHttpRequest, textStatus, errorThrown);
            }
        });
    }
}

function GetClientRID() {
    var rows = grid.getSelectedRows();
    if (!rows.length) { toastrWarning('Please select lines to be processed!<br/>请选择需要处理的行!'); return ""; }
    var ids = [];
    for (var i = 0; i < rows.length; i++) ids.push(rows[i].RID);
    return ids.join(',');
}

var detailWin = null, curentData = null;
function showDetail(data) {
    curentData = data;
    //console.info('showDetail');
    //console.info(curentData);
    if (detailWin) {
        detailWin.show();
    } else {
        //创建表单结构
        var mainform = $("#mainform");
        form=mainform.ligerForm({ inputWidth: 280,
            fields: [
                { name: "RID", type: "hidden" },
                { display: "Function ID", name: "FunID", newline: true, labelWidth: 150, width: 220, space: 30, type: "text" },
                { display: "Function 描述", name: "FunDesc", newline: true, labelWidth: 150, width: 220, space: 30, type: "text" },
                { display: "Action", name: "Action1", newline: true, labelWidth: 150, width: 220, space: 30, type: "select", comboboxName: "Action12",
                    options: { valueFieldID: "Action1", url: "FunctionInf.aspx?Action=LoadFunItem", isMultiSelect: true, split: '/' }
                },
                { name: "Status1", type: "hidden"}]
        });

        detailWin = $.ligerDialog.open({
            title: "Function 管理", target: $("#detail"), width: 450, height: 200, top: 120, allowClose: false, buttons: [{ text: '保存', onclick: function () { save(); } }, { text: '取消', onclick: function () { detailWin.hide(); HideTip(); } }]
        });
    }
    if (curentData.RID != '') {
        if (curentData.ActID)
            $("#Action12").ligerComboBox().selectValue(curentData.ActID);
        else
            $("#Action12").ligerComboBox().selectValue('');

        $("#RID").val(curentData.RID);
        $("#FunID").val(curentData.FunID);
        $("#FunDesc").val(curentData.FunDesc);
        $("#Action1").val(curentData.ActID);
        $("#Action12").val(curentData.ActDesc);
        $("#Status1").val(curentData.Flag);
        $("#FunDesc").focus();
        $("#FunID").ligerGetTextBoxManager().setDisabled();
    } else {
        $("#Action12").ligerComboBox().selectValue('');
        $("#RID").val('');
        $("#FunID").val('');
        $("#FunID").ligerGetTextBoxManager().setEnabled();
        $("#FunDesc").val('');
        $("#Action1").val('');
        $("#Status1").val("A");
        $("#FunID").focus();
    }
    $("#FunID").attr("maxlength", 20);
    $("#FunDesc").attr("maxlength", 50);


    function save() {
        HideTip();
        curentData = curentData || {};
        var formData = form.getData();
        curentData.RID = formData.RID;
        curentData.FunID = formData.FunID;
        curentData.FunDesc = $.trim(formData.FunDesc);
        curentData.ActID = formData.Action1;
        curentData.Flag = formData.Status1;

        if (curentData.FunID == "") {
            $("#FunID").ligerTip({ content: "Cannot be blank/不允许为空!" }); $("#FunID").select(); return false;
        }
        else if (curentData.FunID.length > 4) {
            $("#FunID").ligerTip({ content: "The maximum length is 4/最大长度4!" }); $("#FunID").select(); return false;
        }

        if (curentData.FunDesc == "") {
            $("#FunDesc").ligerTip({ content: "Cannot be blank/不允许为空!" }); $("#FunDesc").select(); return false;
        }


        //console.info('formData+curentData:');
        //console.info(formData);
        //console.info(curentData);
        var _url = url + "Action=Save";
        $.ajax({ cache: false, async: true, url: _url, data: curentData, dataType: 'text', type: 'post',
            success: function (res) {
                grid.loadData();
                switch (res) {
                    case "existed":
                        toastrWarning('Function ID is already exists, please try another!<br/>功能编码已经存在,请重新输入!');
                        break;
                    case "":
                        toastrSuccess('Saved/保存成功!');
                        detailWin.hide();
                        break;
                    default:
                        toastrError(res);
                        break;
                }
            },
            error: function (message) {
                if (message.responseText == "True") {
                    grid.loadData();
                    toastrSuccess('Saved/保存成功!');
                    detailWin.hide();
                } else {
                    toastrError('Error! Not saved/保存失败!');
                }
            }
        });
    }

    function HideTip() {
        $("#FunID").ligerHideTip();
        $("#FunDesc").ligerHideTip();
        //$("#Action12").ligerComboBox().selectValue('');
        //$("#Action12").val('');
    }
}

function ShowError(fun, XMLHttpRequest, textStatus, errorThrown) {
    var mess = "出错了! 请联系管理员!<br/>";
    mess += "function:" + fun + "<br/>";
    mess += "XMLHttpRequest.status:" + XMLHttpRequest.status + "<br/>";
    mess += "XMLHttpRequest.readyState:" + XMLHttpRequest.readyState + "<br/>";
    mess += "textStatus:" + textStatus;
    toastrError(mess);
}